package cn.codergege.demo.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;


@Profile({"development", "test"})
@Configuration
@PropertySource("classpath:/development/db.properties")
public class DevDataSourcePrimaryConfig implements DataSourceConfig {

        @Autowired
        private Environment env;

        private String getEnvProperty(String propertyName) {
            return env.getProperty(propertyName);
        }

        private int getIntEnvProperty(String propertyName) {
            return Integer.parseInt(env.getProperty(propertyName));
        }

        @Override
        @Bean(name = "primaryDs")
        public DataSource createDataSource() {
            System.out.println("----> development, test: dataSource ");
            ComboPooledDataSource ds = new ComboPooledDataSource();
            try {
                ds.setDriverClass(getEnvProperty("jdbc.driver"));
                ds.setJdbcUrl(getEnvProperty("jdbc.url"));
                ds.setUser(getEnvProperty("jdbc.username"));
                ds.setPassword(getEnvProperty("jdbc.password"));

                ds.setInitialPoolSize(getIntEnvProperty("initialSize"));
                ds.setMaxPoolSize(getIntEnvProperty("maxSize"));
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }

            return ds;
        }
}
			
			